<template>
    <div>
    <basic-container>
      <avue-crud
        :option="tableOption"
        :data="tableData"
        :table-loading="tableLoading"
        ref="crud"        
        @row-save="handleSave"
        @row-del="handleDel"
        @refresh-change="handleRefreshChange"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        @selection-change="handleSelectionChange"
        @row-update="handleUpdate"
        @search-change="handleSearchChange"
      >
      <template slot="menuLeft">
        
        <!-- <el-button
          type="danger"
          @click="handleBathDelRows"
          :loading="bachDeleting"
          v-perm="'goods_category/batch-remove'"
          icon="el-icon-remove"
          size="small"
        >批量删除</el-button> -->
        <el-button
        type="primary"
        @click="handleExport"
        :loading="downloadLoading"
        icon="el-icon-download"
        v-perm="'goods_category/export'"
        size="small"
      >导出</el-button>
      </template>
      </avue-crud>
      </basic-container>
    </div>
  </template>
  <script>
  import { validatenull } from "@/util/validate";
  import { filterForm } from "@/util/util";
  // import { DIC } from "@/const/dic";
  import {  getLabelFromDicV2 } from "@/const/dic";
  import { nowDate } from "../../util/date";
  import * as apiObj from "../../api/goodsCategory";
  import { goodsCategoryTableOption} from "@/const/goodsCategory/goodsCategoryTableOption.js";
  
  export default {
    data() {
      return {
        bachDeleting: false,
        tableOption: {}, //表格设置属性
        tableData: [], //表格的数据
        downloadLoading:false,
        tableLoading: false,
        tableQueryParam: {},
        page: {
          total: 0, //总页数
          currentPage: 1, //当前页数
          pageSize: 10 //每页显示多少条
        }
      };
    },
    created() {
      //初始化数据格式
      this.tableOption = goodsCategoryTableOption;
      this.handleList();
    },
    methods: {
      handleCurrentChange(page) {
        this.page.currentPage = page;
        this.handleList();
      },
      handleSizeChange(size) {
        this.page.pageSize = size;
        this.handleList();
      },
    
    handleBathDelRows() {
        if (validatenull(this.currentSelectedRowIds)) {
          this.$notify({
            showClose: true,
            message: "请至少选择一行要删除的数据",
            type: "error"
          });
          return false;
        }
        this.$confirm('是否确认删除所选择记录吗', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.bachDeleting = true;
          apiObj.removeByIds(
            this.currentSelectedRowIds
          ).then(() => {
              this.bachDeleting = false;
              this.handleList();
              this.$message({
                showClose: true,
                message: "成功",
                type: "success"
              });
              this.$refs.crud.selectClear();
            })
            .catch(() => {
              this.bachDeleting = false;
            });
        });
      },
    
      handleSelectionChange(args) {
        this.currentSelectedRowIds = args.map(el => el.id);
      },
      hasChanged(params1,params2){
        return Object.keys(params1).some(key=>params2[key] != params1[key]);
    },
    handleSearchChange(params) {
      if(this.hasChanged(params,this.tableQueryParam)){
        this.page.currentPage = 1;
      }
        this.tableQueryParam = params;
        this.handleList();
      },
      
      /**
       * @title 数据更新
       * @param row 为当前的数据
       * @param index 为当前更新数据的行数
       * @param done 为表单关闭函数
       *
       **/
      handleUpdate(row, index, done, reject) {
        apiObj.update(row)
          .then(() => {
            this.handleList();
            this.$message({
              showClose: true,
              message: "修改成功",
              type: "success"
            });
            done();
          })
          .catch(() => {
            reject();
          });
      },      
      
      /**
       * @title 数据添加
       * @param row 为当前的数据
       * @param done 为表单关闭函数
       *
       **/
      handleSave(row, done, reject) {
        // row.parentId=0
        apiObj.create(row)
          .then(() => {
            this.handleList();
            this.$message({
              showClose: true,
              message: "添加成功",
              type: "success"
            });
            done();
          })
          .catch(() => {
            reject();
          });
      },
      handleRefreshChange() {
        this.handleList();
      },
      /**
       * @title 获取数据
       * @detail 赋值为tableData表格即可
       *
       **/
      handleList() {
        this.tableLoading = true;
        apiObj.list({
          pageNo: this.page.currentPage,
          pageSize: this.page.pageSize,
          ...this.tableQueryParam
        })
          .then(data => {
            this.tableData = data || [];
            // this.page.total = data.totalRecord;
            this.tableLoading = false;
          })
          .catch(() => {
            this.tableLoading = false;
          });
      },     
      
      handleDel(row, index) {
        this.$confirm('是否确认删除', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            apiObj.removeById(
              row.id
            ).then(() => {
              this.handleList();
              this.$message({
                showClose: true,
                message: "删除成功",
                type: "success"
              });
              this.$refs.crud.selectClear();
            });
          })
          .catch(() => {});
      },    
      handleExport() {
        this.downloadLoading = true;
        apiObj.list({
          pageNo: 1,
          pageSize: 3000,
          ...filterForm(this.$refs.crud.searchForm)
        }).then(res => {
          import("@/vendor/Export2Excel").then(excel => {
            const tHeader = ["商品分类名称","是否前端显示","排序顺序","创建时间","修改时间","创建人","修改人"];
            const filterVal = ["categoryName","showFlag","sortNum","createTime","modifyTime","creator","modifier"];
            const data = this.formatJson(filterVal, res);
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: "商品分类表" + nowDate()
            });
            this.downloadLoading = false;
          });
        });
      },
      formatJson(filterVal, jsonData) {      
        return jsonData.map(v =>
          filterVal.map(j => {
            return getLabelFromDicV2(this.$refs.crud.DIC,j,v[j]);
          })
        );
      }
    }
  };
  </script>
